package com.zzj.ecology.framework.configs.security.handler;

import com.zzj.ecology.common.constant.Constant;
import com.zzj.ecology.common.utils.MessageUtils;
import com.zzj.ecology.framework.manager.AsyncManager;
import com.zzj.ecology.framework.manager.async.AsyncTaskFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * 登出处理逻辑
 */
@Component
public class CustomizeLogoutHandler implements LogoutHandler {

    protected final Log logger = LogFactory.getLog(this.getClass());
    private boolean invalidateHttpSession = true;
    private boolean clearAuthentication = true;

    @Autowired
    private AsyncTaskFactory asyncTaskFactory;
    @Autowired
    private AsyncManager asyncManager;

    public CustomizeLogoutHandler() {}

    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        Assert.notNull(request, "HttpServletRequest required");
        if (this.invalidateHttpSession) {

            asyncManager.execute(asyncTaskFactory.recordLoginInfor(authentication.getName(),
                    Constant.LOGIN_SUCCESS,
                    new Date(),
                    MessageUtils.message("user.logout.success")));

            HttpSession session = request.getSession(false);
            if (session != null) {
                this.logger.debug("Invalidating session: " + session.getId());
                session.invalidate();
            }
        }

        if (this.clearAuthentication) {
            SecurityContext context = SecurityContextHolder.getContext();
            context.setAuthentication((Authentication)null);
        }

        SecurityContextHolder.clearContext();
    }

    public boolean isInvalidateHttpSession() {
        return this.invalidateHttpSession;
    }

    public void setInvalidateHttpSession(boolean invalidateHttpSession) {
        this.invalidateHttpSession = invalidateHttpSession;
    }

    public void setClearAuthentication(boolean clearAuthentication) {
        this.clearAuthentication = clearAuthentication;
    }
}
